import React, { useEffect, useState } from "react";
import { useContext } from "react";
import { AllContext } from "@src/Common/AllContext";
import { http_request, ac_cgi_url } from "@src/Common/Request";
import "./transfer.css";
import { Transfer, Tabs, Input, Button, Space } from "antd";
import type { TransferProps, TabsProps } from "antd";
import ManualAddDevice from "./ManualAddDevice";

interface Device {
  devType: string;
  mac: string;
  groupId: string;
  model: string;
  binded: boolean;
}

interface RecordType {
  key: string;
  title: string;
  description: string;
  chosen: boolean;
}

const AddDevice: React.FC = () => {
  const [originalDevices, setOriginalDevices] = useState<Device[]>([]);
  const [leftData, setLeftData] = useState<RecordType[]>([]);
  const [rightData, setRightData] = useState<React.Key[]>([]);
  const [manualMac, setManualMac] = useState("");
  const baseContext = useContext(AllContext);
  const { devType, group, messageApi, closeDrawer } = baseContext;

  const get_devs = async () => {
    try {
      const request_params = new URLSearchParams();
      request_params.set("devType", devType);
      request_params.set("action", "get_devs");
      request_params.set("groupId", group.groupId);

      const response = await http_request(
        `${ac_cgi_url}?${request_params}`,
        request_params,
        "GET",
        {}
      );

      if (response.success) {
        const devices = Array.isArray(response.data) ? response.data : [];

        const bindedKeys = devices
          .filter((dev: Device) => dev.binded)
          .map((dev: Device) => String(dev.mac));

        const allDevices = devices.map((dev: Device) => ({
          key: String(dev.mac),
          title: dev.devType,
          description: `${dev.model}-${dev.mac}`,
          chosen: dev.binded,
        }));

        setOriginalDevices(devices);
        setLeftData(allDevices);
        setRightData(bindedKeys);
      } else {
        messageApi.error(response.msg || "获取设备列表失败");
      }
    } catch (error) {
      messageApi.error("网络请求异常");
    }
  };

  useEffect(() => {
    get_devs();
  }, []);

  const handleChange: TransferProps["onChange"] = (
    newTargetKeys,
    direction,
    moveKeys
  ) => {
    setRightData(newTargetKeys);
  };

  const handleSearch: TransferProps["onSearch"] = (dir, value) => {
  };

  const filterOption = (inputValue: string, option: RecordType) =>
    option.description.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;

  const renderItem = (item: RecordType) => {
    const customLabel = (
      <span className="custom-item">
        {item.title} - {item.description}
      </span>
    );

    return {
      label: customLabel,
      value: item.title,
    };
  };

  const set_devs = (devices: Device[]) => {
    const requestData = {
      action: "set_devs",
      devType: devType,
      dev_list: devices,
    };

    return http_request(ac_cgi_url, requestData, "PATCH", {})
      .then(responseObject => {
        if (!responseObject.success) {
          messageApi.warning(responseObject.msg || "failed");
          return false;
        }
        messageApi.success(responseObject.msg || "success");
        get_devs();
        return true;
      })
      .catch(error => {
        messageApi.error("请求异常");
        return false;
      });
  };

  const handleSubmit = async () => {
    const finalDevices = originalDevices.map((dev) => ({
      ...dev,
      binded: rightData.includes(String(dev.mac)),
    }));

    const success = await set_devs(finalDevices);
    if (success) {
      closeDrawer();
    }
  };

  const handleReset = () => {
    setRightData([]);
  };

  // 定义 Tabs 的 items
  const tabItems: TabsProps['items'] = [
    {
      key: "auto",
      label: "自动发现",
      children: (
        <div className="transfer-container">
          <Transfer
            dataSource={leftData.map((item) => ({
              ...item,
              context: baseContext,
            }))}
            className="transfer-list"
            listStyle={{
              width: "100%",
              minHeight: "calc(100vh - 300px)",
              margin: "auto",
            }}
            showSearch
            filterOption={filterOption}
            titles={["未绑定", "已/将绑定"]}
            targetKeys={rightData}
            onChange={handleChange}
            render={renderItem}
            onSearch={handleSearch}
            pagination
            footer={({ direction }) =>
              direction === "right" ? (
                <div
                  style={{
                    position: "relative",
                    borderTop: "1px solid #e9e9e9",
                    padding: "16px 24px",
                    background: "#fafafa",
                    textAlign: "right",
                    boxShadow: "0 -2px 8px rgba(0, 0, 0, 0.1)",
                    borderRadius: "0 0 4px 4px",
                    marginTop: "16px",
                  }}
                >
                  <Space>
                    <Button
                      size="small"
                      onClick={handleReset}
                      disabled={rightData.length === 0}
                    >
                      重置
                    </Button>
                    <Button
                      type="primary"
                      size="small"
                      onClick={handleSubmit}
                      disabled={rightData.length === 0}
                    >
                      提交
                    </Button>
                  </Space>
                </div>
              ) : null
            }
          />
        </div>
      ),
    },
    {
      key: "manual",
      label: "手动添加",
      children: (
        <div style={{ padding: "12px 16px" }}>
          <ManualAddDevice onSuccess={get_devs} />
          <div style={{ 
            marginTop: 16, 
            padding: 12,
            backgroundColor: '#f8f9fa',
            borderRadius: 4 
          }}>
            <p style={{ marginBottom: 8, fontSize: 12 }}>操作说明：</p>
            <ul style={{ 
              fontSize: 12, 
              color: "#666",
              listStyleType: 'circle',
              paddingLeft: 20,
              margin: 0 
            }}>
              <li>支持批量添加多个MAC地址</li>
              <li>MAC地址格式：00:11:22:33:44:55</li>
              <li>添加后设备自动上线</li>
              <li>批量备注一致，后可在设备列表单独修改</li>
            </ul>
          </div>
        </div>
      ),
    },
  ];

  return (
    <Tabs defaultActiveKey="auto" style={{ padding: "0 16px" }} items={tabItems} />
  );
};

export default AddDevice;
